
<template>
  <div style="display: flex">
    <a-tree
      style="font-size: 20px;  margin: 10px"
      class="draggable-tree"
      :default-expanded-keys="expandedKeys"
      draggable
      :tree-data="gData"
      @drop="onDrop"
      @select="onSelect"
      @expand="onExpand"
    />
    <div style="margin-left: 100px;">
      <a-button style="margin: 10px" type="primary" @click="onChange" :disabled="change == false">保存顺序</a-button>
      <!-- <a-button style="margin: 10px" type="primary" @click="onChange" :disabled="change == false">新增</a-button> -->
      <!-- <a-form  :form="form" @submit="handleSubmit">
        <a-form-item label="123" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            v-decorator="['userName', { rules: [{ required: true, message: 'Please input your username!' }] }]"
            placeholder="Username"
          >
          </a-input>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            v-decorator="['password', { rules: [{ required: true, message: 'Please input your Password!' }] }]"
            type="password"
            placeholder="Password"
          >
          </a-input>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-button type="primary" html-type="submit">提交</a-button>
        </a-form-item>
      </a-form> -->
    </div>

    <!-- 
  <a-collapse v-model="activeKey" style="width: 200px;">
      <a-collapse-panel v-for="item in gData" :key="item.id" :header="item.text">
        <p>{{item.text }}</p>
      </a-collapse-panel>
  </a-collapse>
 -->

    <!-- <div style="flex: 0.3">
      <draggable v-model="gData" animation="500" force-fallback="true" handle=".mover" :group="1" @end="onEnd">
        <div v-for="item in gData" :key="item.id" style="user-select: none">
          <div style="width: 100px; height: 30px; display: flex; font-size: 20px; margin: 10px 0px">
            <span class="mover">
              <a-icon type="plus" />
            </span>
            <span
              @click="
                expandarr.includes(item.id) ? expandarr.splice(expandarr.indexOf(item.id), 1) : expandarr.push(item.id)
              "
              >{{ item.text }}</span
            >
          </div>
          <draggable
            v-if="expandarr.includes(item.id)"
            v-model="item.children"
            animation="500"
            force-fallback="true"
            handle=".mover"
            :group="1"
            @end="onEnd"
          >
            <div v-for="i in item.children" :key="i.id" style="user-select: none; margin-left: 20px">
              <div style="width: 130px; height: 20px; font-size: 18px; margin: 6px 0px">
                <span class="mover">
                  <a-icon type="plus" />
                </span>
                <span
                  @click="
                    expandarr.includes(i.id) ? expandarr.splice(expandarr.indexOf(i.id), 1) : expandarr.push(i.id)
                  "
                  >{{ i.text }}</span
                >
              </div>
              <draggable
                v-if="expandarr.includes(i.id)"
                v-model="i.children"
                animation="500"
                force-fallback="true"
                handle=".mover"
                :group="1"
                @end="onEnd"
              >
                <div v-for="j in i.children" :key="j.id" style="user-select: none; display: flex; margin-left: 20px">
                  <div style="width: 100px; height: 20px; font-size: 15px">
                    <span class="mover">
                      <a-icon type="plus" />
                    </span>
                    <spanf
                      @click="
                        expandarr.includes(j.id) ? expandarr.splice(expandarr.indexOf(j.id), 1) : expandarr.push(j.id)
                      "
                      >{{ j.text }}</spanf
                    >
                  </div>
                </div>
              </draggable>
            </div>
          </draggable>
        </div>
      </draggable>
      <a-button type="primary" @click="onChange" :disabled="change == false">保存</a-button>
    </div> -->
  </div>
</template>

<script>
import { postAction, getAction } from '@/api/manage'
import draggable from 'vuedraggable'
import { defineComponent } from 'vue'

export default {
  components: {
    draggable,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      activeKey: ['2'],
      change: false,
      visible: false,
      gData: [],
      expandedKeys: ['0-0', '0-0-0', '0-0-0-0'],
      expandarr: [],
      onNode: '',
      form: this.$form.createForm(this),
    }
  },
  mounted() {
    this.getMenu()
    this.$nextTick(() => {
      // To disabled submit button at the beginning.
      this.form.validateFields()
    })
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
        }
      })
    },
    onChange() {
      console.log(this.gData)
postAction('/function/updateMenu',  this.gData ).then((res) => {
  if (res.code == 200) {
      this.$message.success(res.msg)
    this.change = false
    this.getMenu()
    setTimeout(1000)
    alert('即将重启页面')
    location.reload();
  }else{
 this.$message.error(res.msg)
  }
})
    },
    onEnd() {
      this.change = true
    },
    onExpand(expandedKeys) {
      //  this.expandarr=expandedKeys
      console.log('onExpand', expandedKeys)
    },
    getTreeHeight(data) {
      if (!data.children || data.children.length === 0) {
        return 1
      }

      let maxHeight = 0
      data.children.forEach((child) => {
        const childHeight = this.getTreeHeight(child)
        maxHeight = Math.max(maxHeight, childHeight)
      })
      return maxHeight + 1
    },
    handleOk() {
      this.visible = false
    },
    onSelect(key) {
      console.log(key)
      this.onNode = key[0]
      // getAction('/function/menuDetail', { id: this.onNode }).then((res) => {})
    },
    getMenu() {
      postAction('/function/findMenuByPNumberAll')
        .then((result) => {
          if (result.code == 200) {
          let dataTree = []
          result.data.forEach((item, index) => {
            dataTree.push(this.toTree(item))
          })
          this.gData = dataTree
          }else{
            this.$message.error(result.msg)
          }
        })
        .catch((err) => {})
    },
    toTree(item) {
      let node = {
        title: item.text,
        key: item.id,
        scopedSlots: { title: 'title' },
      }
      Object.assign(node, item)
      if (item.children) {
        node.children = []
        item.children.forEach((item, index) => {
          node.children.push(this.toTree(item))
        })
      }
      return node
    },
    // onDragEnter(info) {
    //   console.log(info)
    //   // expandedKeys 需要受控时设置
    //   // this.expandedKeys = info.expandedKeys
    // },
    onDrop(info) {
      const dropKey = info.node.eventKey
      const dragKey = info.dragNode.eventKey
      const dropPos = info.node.pos.split('-')
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
      const loop = (data, key, callback) => {
        data.forEach((item, index, arr) => {
          if (item.key === key) {
            return callback(item, index, arr)
          }
          if (item.children) {
            return loop(item.children, key, callback)
          }
        })
      }
      const data = [...this.gData]

      // Find dragObject
      let dragObj
      loop(data, dragKey, (item, index, arr) => {
        arr.splice(index, 1)
        dragObj = item
      })
      if (!info.dropToGap) {
        // Drop on the content
        loop(data, dropKey, (item) => {
          item.children = item.children || []
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.push(dragObj)
        })
      } else if (
        (info.node.children || []).length > 0 && // Has children
        info.node.expanded && // Is expanded
        dropPosition === 1 // On the bottom gap
      ) {
        loop(data, dropKey, (item) => {
          item.children = item.children || []
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.unshift(dragObj)
        })
      } else {
        let ar
        let i
        loop(data, dropKey, (item, index, arr) => {
          ar = arr
          i = index
        })
        if (dropPosition === -1) {
          ar.splice(i, 0, dragObj)
        } else {
          ar.splice(i + 1, 0, dragObj)
        }
      }
      this.gData = data
      console.log(this.gData)
      console.log('treeData: ', this.getTreeHeight({ children: this.gData }) - 1)
      this.change = true
    },
  },
}
</script>

<style scoped>
a {
  background-color: aquamarine;
}
</style>